﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AOP.Filter.Jurisdiction;
using AOP.Filter.Login;
using AOP.Filter.Result;
using CacheService.Standard;
using Microsoft.AspNetCore.Mvc;
using MODEL.Model;
using SERVICE.Admin.IService;

namespace Admin.Controllers
{
    [NoJurisdiction,NoLogin]
    public class LoginController : Controller
    {
        ICache cache;
        ISyetemService syetemService;
        public LoginController(ICache cache, ISyetemService syetemService)
        {
            this.cache = cache;
            this.syetemService = syetemService;
        }
        [Native]
        public IActionResult Index()
        {
            return View();
        }
        [Native]
        public IActionResult Out()
        {
            try
            {
                var key = Request.Cookies["key"];
                Response.Cookies.Delete("key");
                cache.delete(key);
            }
            catch
            {
            }
            return Redirect("/login");
        }
        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="name">账号</param>
        /// <param name="pass">密码</param>
        /// <returns></returns>
        [HttpPost]
        public bool login(string name, string pass)
        {
            var user = syetemService.OnLogin(name, pass);
            var key = Guid.NewGuid().ToString("N");
            var paths = user.SystemRule.SystemJurisdictions.AsParallel().Select(x => x.name).ToList();
            var menus = new List<SystemMenu>();
            foreach (var item in syetemService.GetMenu())
            {
                var ps = item.SystemMenuPaths.AsParallel().Where(x => paths.Contains(x.name)).ToList();
                if (ps.Count > 0)
                {
                    var menu = new SystemMenu()
                    {
                        name = item.name,
                        icon = item.icon,
                        SystemMenuPaths = ps
                    };
                    menus.Add(menu);
                }
            }
            cache.set($"{key}_menus", menus);
            cache.set(key, user);
            Response.Cookies.Append("key", key);
            return true;
        }
    }
}